/**
 * Created by FreezeSoul on 2018/10/24.
 */
define([
    "app/core/base",
    "app/core/util",
    "../../common/commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    'dhtmlxGantt',
    'dhtmlxGantt_cn',
    'dhtmlxgantt_marker',
    'dhtmlxgantt_tooltip',
    'css!app/plugins/controls/vender/dhtmlxGantt/resources/style.css'
], function (Chart, Util, Meta, $, _, JSON, log) {
    //TODO:自定义组件属性
    var property = {
        config: "property",
        option: [
            {
                group: '绑定',
                id: 'GANTT_BINDING',
                name: '数据绑定',
                enable: true,
                type: 'sortBinding',
                dataset: '',
                columns: [],
                tooltip: 'gannt图数据绑定'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var datepicker = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._uuid = "dhtmlxganttChart";
            this._element = null;
            this._container = null;
            this._option = {
                Series: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    config: {
                        "show_grid": false,
                        "readonly": true,
                        "scale_unit": "year",
                        "date_scale": "%Y年-%m月",
                        "subscales": [
                            {
                                "unit": "week",
                                "step": 1,
                                "template": "function(date){var w = date.getDay(), d = date.getDate(); return Math.ceil((d + 6 - w) / 7) + '周';}",
                                "index": 1
                            }
                        ]
                    },
                    tasks: {},
                    markers: []
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _render: function (option) {
            var dhtmlxgantt = document.getElementById(this._uuid);
            if (dhtmlxgantt) {
                gantt.clearAll();
            }

            for (var prop in option.config) {
                if (!option.config.hasOwnProperty(prop)) continue;
                gantt.config[prop] = option.config[prop];
            }

            if (!dhtmlxgantt) {
                $('<div id="dhtmlxganttChart" style="width:100%;height: 100%;"></div>').appendTo(this._container);
                dhtmlxgantt = document.getElementById(this._uuid);
                gantt.init(this._uuid);
            } else {
                $(dhtmlxgantt).show().appendTo(this._container)
            }


            gantt.templates.tooltip_text = function (start, end, event) {
                return "<b>任务:</b> " + event.text + "<br/><b>开始时间:</b> " + gantt.templates.tooltip_date_format(start) + "<br/><b>结束时间:</b> " + gantt.templates.tooltip_date_format(end);
            };

            gantt.templates.task_class = function (start, end, task) {
                return task.task_class_name ? task.task_class_name : "";
            };


            if (option.tasks && option.tasks.data) {
                var copyTask = $.extend(true, {}, option.tasks);
                _.each(copyTask.data, function (task) {
                    if (!(task.start_date instanceof Date)) {
                        task.start_date = new Date(task.start_date);
                    }
                });
                gantt.parse(copyTask);
            }

            if (option.markers && $.isArray(option.markers)) {
                var copyMrkers = $.extend(true, [], option.markers);
                for (var i = 0; i < copyMrkers.length; i++) {
                    var marker = copyMrkers[i];
                    if (!(marker.start_date instanceof Date)) {
                        marker.start_date = new Date(marker.start_date);
                    }
                    gantt.addMarker($.extend(true, {}, marker));
                }
            }
            return dhtmlxgantt;
        },
        example: function () {
            try {
                var exampleOption = $.extend(true, {}, this._option.Option);
                exampleOption.config = {
                    "show_grid": false,
                    "readonly": true,
                    "scale_unit": "year",
                    "date_scale": "%Y年-%m月",
                    "subscales": [
                        {
                            "unit": "week",
                            "step": 1,
                            "template": "function(date){var w = date.getDay(), d = date.getDate(); return Math.ceil((d + 6 - w) / 7) + '周';}",
                            "index": 1
                        }
                    ]
                };
                exampleOption.tasks = {
                    data: [
                        {
                            id: 1,
                            text: "项目 #1",
                            start_date: "2015-04-03",
                            duration: 11,
                            progress: 0.6,
                            open: true,
                            task_class_name: 'gantt_task_red'
                        },
                        {id: 2, text: "项目 #1", start_date: "2015-04-03", duration: 11, progress: 1, open: true},
                        {
                            id: 3,
                            text: "项目 #1",
                            start_date: "2015-04-03",
                            duration: 11,
                            progress: 0.5,
                            open: true,
                            task_class_name: 'gantt_task_blue'
                        },
                        {
                            id: 4,
                            text: "项目 #1",
                            start_date: "2015-04-03",
                            duration: 11,
                            progress: 0.5,
                            open: true,
                            task_class_name: 'gantt_task_blue'
                        },
                        {id: 5, text: "项目 #1", start_date: "2015-04-03", duration: 11, progress: 1, open: true},
                        {
                            id: 6,
                            text: "项目 #1",
                            start_date: "2015-04-03",
                            duration: 11,
                            progress: 0.6,
                            open: true,
                            task_class_name: ''
                        }
                    ],
                    links: [
                        {id: 1, source: 1, target: 2, type: "1"},
                        {id: 2, source: 1, target: 3, type: "1"},
                        {id: 3, source: 3, target: 4, type: "1"},
                        {id: 4, source: 4, target: 5, type: "0"},
                        {id: 5, source: 5, target: 6, type: "0"}
                    ]
                };
                exampleOption.markers = [
                    {
                        start_date: "2015-04-03",
                        css: "gantt_marker_red",
                        text: "Start project",
                        title: "Start project: 03-04-2015"
                    }
                ];
                this._element = this._render(exampleOption);
            } catch (e) {
                log.error(e);
            }
        },
        _bindData: function (data) {
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'sortBinding'});
            if (!bindProperty) return;

            if (!bindProperty.enable) return;
            var dataSetCode = bindProperty.dataset;
            var table = data[dataSetCode];
            if (table && table.length === 1) {
                this._option.Option.tasks = {data: table[0].data, links: table[0].links};
                this._option.Option.markers = table[0].markers;
            }
        },
        setData: function (data) {
            try {
                this._readProperty();
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);
                }
                this._element = this._render(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
                gantt.render();
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).hide().appendTo("body")
            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: datepicker,
        Property: property
    };
});